// ignore_for_file: non_constant_identifier_names, unused_local_variable

import 'dart:collection';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:verse_systems/commom/global/global.dart';
import 'package:verse_systems/commom/models/extend_model.dart';
import 'package:verse_systems/commom/models/payment_confirm_model.dart';
import 'package:verse_systems/commom/models/repayment_bank_info_model.dart';
import 'package:verse_systems/pages/picker/choose_picker_view.dart';
import 'package:verse_systems/pages/repayment/repayment_state.dart';
import 'package:verse_systems/commom/routers/routes_pages_name.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/utils/utils.dart';

// 审核中：18633026212
// 被拒绝：15268117440
// 已放款：16601750925
// 抽奖号码 18768482291

class RepaymentControl extends GetxController {
  MethodChannel eventChannel = const MethodChannel('open_native_camera');

  final RepaymentState state = RepaymentState();

  final TextEditingController real_name_control = TextEditingController();

  static BuildContext context =
      Global.navigatorKey.currentState!.overlay!.context;

  //还款凭证上传
  //
  repayment_bank_info_onPressed() async {
    //    state.repayment_bank_info_repay_id
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    if (state.repayment_bank_info_repay_info_id == "null") {
      map['repay_info_id'] = null;
    } else {
      map['repay_info_id'] = state.repayment_bank_info_repay_info_id;
    }
    map['voucher'] = state.repayment_bank_info_path;

    Request.postCallback(
      HttpUrls.voucherUpload,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("还款凭证上传-----$result");
        if (result.status == 0) {
          Loading.toast("upload_success".tr);
        }
      },
      error: (err) {},
    );
  }

  openAlbum() {
    eventChannel.invokeMethod("open_album").then((value) async {
      if (Platform.isAndroid) {
        if (value == true) {
          //获取相册授权
          String base64 = await Utils.openAlbum();
          uploadImage(base64: base64);
        }
      } else {
        String base64 = value["image"];
        uploadImage(base64: base64);
      }
    });
  }

  uploadImage({String? base64}) async {
    Loading.show("上传中...");
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    map['img_type'] = "repayment-voucher";
    map['base64'] = base64;

    Request.postCallback(
      HttpUrls.uploadUrl,
      data: map,
      success: (res) async {
        Loading.dismiss();
        ResultData result = ResultData.fromJson(res.data);

        if (result.status == 0) {
          String url = result.data["url"];
          debugPrint("上传还款凭证图片result-----$result");
          state.repayment_bank_info_voucher = url;
          state.repayment_bank_info_path = result.data["path"];
          update();
        }
      },
      error: (err) {
        Loading.dismiss();
      },
    );
  }

//还款确认
  repayment_confirm() {
    if (real_name_control.text.trim() == '') {
      return Loading.showError("confirm_pay_name_to_submit".tr);
    }

    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['type'] = "repay";
    map['borrow_id'] = borrowId;
    map['extend_day'] = 0;
    map['real_name'] = real_name_control.text;
    Get.toNamed(RoutesPage.RepaymentonBankInfo, arguments: map);
  }

//展期确认
  repayment_extend() {
    if (real_name_control.text.trim() == '') {
      return Loading.showError("confirm_pay_name_to_submit".tr);
    }
    if (state.extend.trim() == '' || state.extend.trim() == 'please_select_days_roll'.tr) {
      return Loading.showError("please_select_days_roll".tr);
    }

    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['type'] = "extend";
    map['borrow_id'] = borrowId;
    map['extend_day'] = state.extend;
    map['real_name'] = real_name_control.text;
    Get.toNamed(RoutesPage.RepaymentonBankInfo, arguments: map);
  }

//获取还款(银行信息页面数据) repaymentConfirmation
  get_repaymenton_bank_infos() async {
    Loading.show("加载中...");
    final String token = await AccountUtil.getUserToken();
    final Map<String, dynamic> map = Get.arguments;
    map['token'] = token;
    Request.postCallback(
      HttpUrls.repaymentConfirmation,
      data: map,
      success: (res) async {
        Loading.dismiss();
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("获取还款(银行信息页面数据)--$result");
        if (result.status == 0) {
          final Map<String, dynamic> json = result.data["data"]["bank"];
          // json["vouchers"] = true;
          final Map<String, dynamic> data = result.data["data"];
          state.dataBank = RepaymentDataBank.fromJson(json);
          state.bankInfo = RepaymentBankInfo.fromJson(data);

          state.repayment_bank_info_url = result.data["data"]["url"];
          state.repayment_bank_info_type = result.data["type"];
          state.repayment_bank_info_notice = result.data["notice"];
          state.repayment_bank_info_repay_amount =
              result.data["repay_amount"].toString();
          state.repayment_bank_info_repay_info_id =
              result.data["repay_info_id"].toString();
          final int time = result.data["countdown"];
          compute(time: time);
        }
      },
      error: (err) {
        Loading.dismiss();
      },
    );
  }

  compute({required int time}) {


    DateTime startDate = DateTime.fromMillisecondsSinceEpoch(time * 1000);
    // DateTime startDate =
    //     DateTime.fromMillisecondsSinceEpoch(int.parse("1696696954") * 1000);
    DateTime endDate = DateTime.now();
    int seconds = endDate.difference(startDate).inSeconds;

    // debugPrint("startDate----->$startDate");
    // debugPrint("endDate----->$endDate");
    // debugPrint("timeStrpp----->$seconds");
    if (seconds < 0) {
      debugPrint("我是负数----->$seconds");
      state.repayment_bank_info_countdown = (seconds * -1);
    } else {
      state.repayment_bank_info_countdown = seconds;
    }
    update();
  }

  handleOnExtend() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: false,
      builder: (ctx) {
        return ChoosePickerView(
          onResult: (result) {
            state.extend = result["value"].toString();
            update();
            extendStepTwo();
          },
          params: state.extend_day,
        );
      },
    );
  }

  extendStepOne() async {
    final borrowId = Get.arguments["borrow_id"];
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    Request.postCallback(
      HttpUrls.extendStepOne,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("extendStepOne--$result");
        if (result.status == 0) {
          state.real_name = result.data["real_name"];
          final List extend_day = result.data["extend_day"];
          List extend = [];
          for (var element in extend_day) {
            extend.add({"key": 0, "value": element});
          }
          state.extend_day = extend;
          debugPrint("extend--$extend");
          update();
        }
      },
    );
  }

  extendStepTwo() async {
    final borrowId = Get.arguments["borrow_id"];
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    map['extend_day'] = state.extend;
    Request.postCallback(
      HttpUrls.extendStepTwo,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("extendStepTwo--$result");
        if (result.status == 0) {
          final List details = result.data["details"];
          state.extendList =
              details.map((json) => ExtendModel.fromJson(json)).toList();
          update();
        }
      },
    );
  }

  repaymentConfirm() async {
    final borrowId = Get.arguments["borrow_id"];
    final String token = await AccountUtil.getUserToken();
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    Request.postCallback(
      HttpUrls.repaymentConfirm,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("repaymentConfirm--$result");
        if (result.status == 0) {
          final Map<String, dynamic> json = result.data;
          state.payment = PaymentConfirmModel.fromJson(json);
          update();
        }
      },
    );
  }
}
